package com.wswy.wzcx.ui.adapter;


import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.util.SparseArrayCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bytedance.sdk.openadsdk.TTFeedAd;
import com.che.libcommon.api.page.PageAdapterWrapper;
import com.che.libcommon.api.page.Pagination;
import com.che.libcommon.ui.adapter.OnItemClickListener;
import com.facebook.common.util.UriUtil;
import com.qq.e.ads.nativ.NativeExpressADView;
import com.wswy.wzcx.AppContext;
import com.wswy.wzcx.R;
import com.wswy.wzcx.model.home.RouterUtils;
import com.wswy.wzcx.model.news.NewsModel;
import com.wswy.wzcx.statistics.StatTools;
import com.wswy.wzcx.ui.hold.ViewHolder;
import com.wswy.wzcx.ui.other.ClickUtils;
import com.wswy.wzcx.ui.web.WebPageArgument;
import com.wswy.wzcx.ui.web.WebViewActivity;
import java.util.HashMap;
import java.util.List;

public class NewsAdapter3 extends PageAdapterWrapper<Object,RecyclerView.ViewHolder> {

    private static final String TAG = "NewsAdapter3";

    private static final int TYPE_NORMAL = 0;
    private static final int TYPE_AD_01 = 1;

    private static final int TYPE_NEWS_PIC3 = 5;

    private SparseArrayCompat<Boolean> readMap = new SparseArrayCompat<>();
    private HashMap<NativeExpressADView, Integer> mAdViewPositionMap;

    public NewsAdapter3(Pagination<Object> pagination,final String type,final String statType) {
        super(pagination);

        setOnItemClickListener(new OnItemClickListener<Object>() {
            @Override
            public void onItemClick(View itemView, int position, Object o) {

                if (ClickUtils.isFastClick()){
                    return;
                }

                if (o instanceof NewsModel){
                    NewsModel model = ((NewsModel) o);
                    Context context = itemView.getContext();

                    WebPageArgument argument=new WebPageArgument(model.link);
                    argument.setTitle("热门资讯");
                    argument.setShowToolBar(true);
                    argument.setShowUrlTitle(false);
                    argument.setShowAd(false);
                    argument.setShowShare(true);
                    argument.setShowBannerAd(true);
                    RouterUtils.startWeb(context,argument);
                    //WebViewActivity.startWebview(context, "热门资讯", model.link, true,true,true,false);
                    readMap.put(model.id,true);
                    notifyItemChanged(position);

                    if (type != null) {
                        if (statType == null) {
                            StatTools.sendClickNew(AppContext.getContext(), type, position);
                        } else {
                            StatTools.sendClickNew(AppContext.getContext(), statType, type, position);
                        }
                    }


                }

            }
        });

    }

    public void setAdViewPositionMap(
        HashMap<NativeExpressADView, Integer> mAdViewPositionMap) {
        this.mAdViewPositionMap = mAdViewPositionMap;
    }

    @Override
    public int getItemViewType(int position) {
        Object item = getItemData(position);
        if (item instanceof NewsModel) {
            return ((NewsModel) item).hasPics()? TYPE_NEWS_PIC3 :TYPE_NORMAL;
        } else if (item instanceof NativeExpressADView) {
            //广点通
            return TYPE_AD_01;
        } else if (item instanceof TTFeedAd){
            //头条广告
            TTFeedAd ad = (TTFeedAd) item;

            return TTADViewHolders.getViewType(ad,super.getItemViewType(position));
        }else {
            return super.getItemViewType(position);
        }
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);

        if (viewType == TYPE_NORMAL){
            return new NewsVH(inflater.inflate(R.layout.news_item, parent, false));
        } else if(viewType == TYPE_NEWS_PIC3){
            return new NewsPic3VH(inflater.inflate(R.layout.news_item_img3, parent, false));
        }else if (viewType == TYPE_AD_01){
            return new AD01VH(inflater.inflate(R.layout.ad01_item, parent, false));
        }else if (TTADViewHolders.isTTADType(viewType)){
            return TTADViewHolders.createViewHolder(parent, viewType);
        }

        return null;
    }

    // 把返回的NativeExpressADView添加到数据集里面去
    public void addADViewToPosition(int position, NativeExpressADView adView) {
        if (position >= 0 && position < getItemCount() && adView != null) {
            getDatas().add(position, adView);
        }
    }

    public void addTDADs(int position,TTFeedAd ttFeedAd){
        if (position >= 0 && position < getItemCount()) {
            getDatas().add(position,ttFeedAd);
        }

    }

    // 移除NativeExpressADView的时候是一条一条移除的
    public void removeADView(int position, NativeExpressADView adView) {
        getDatas().remove(position);
        mAdViewPositionMap.remove(adView);
        notifyDataSetChanged();
        //notifyItemRemoved(position); // position为adView在当前列表中的位置
        //notifyItemRangeChanged(0, getItemCount() - 1);
    }



    @Override
    protected void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position,
        Object item) {
        if (holder instanceof NewsVH && item instanceof NewsModel) {
            //((NewsVH) holder).bind((NewsModel) item);

            bindNews(((NewsVH) holder), ((NewsModel) item));
        }else if(holder instanceof AD01VH){
            AD01VH customViewHolder= (AD01VH) holder;
            final NativeExpressADView adView = (NativeExpressADView) getItemData(position);
            mAdViewPositionMap.put(adView, position); // 广告在列表中的位置是可以被更新的
            if (customViewHolder.container.getChildCount() > 0
                && customViewHolder.container.getChildAt(0) == adView) {
                return;
            }


            if (customViewHolder.container.getChildCount() > 0) {
                customViewHolder.container.removeAllViews();
            }

            if (adView.getParent() != null) {

                ((ViewGroup) adView.getParent()).removeView(adView);
            }


            customViewHolder.container.addView(adView);
            adView.render(); // 调用render方法后sdk才会开始展示广告
        }else if (TTADViewHolders.isTTADViewHolder(holder)){
            TTFeedAd ttFeedAd = (TTFeedAd) getItemData(position);
            TTADViewHolders.bindViewHolder(holder,position,ttFeedAd,ttadCloseClickListener);
        }

    }


    private View.OnClickListener ttadCloseClickListener=new OnClickListener() {
        @Override
        public void onClick(View v) {
            Object idx = v.getTag(R.id.item_position);
            Object tag = v.getTag(R.id.item_data);

            if (idx instanceof Integer && tag instanceof TTFeedAd){

                int pos = (int) idx;

                if (pos >=0 && pos < getItemCount()){
                    if (getItemData(pos) == tag){

                        getDatas().remove(pos);

                        notifyItemRemoved(pos);
                    }
                }
            }
        }
    };


    private void bindNews(NewsVH holder,NewsModel item){
        holder.tvTitle.setText(item.topic);
        holder.tvContent.setText(TextUtils.concat(item.source, "  · ",DateFormat.format("MM-dd HH:mm",item.time*1000L) ));


        holder.bindNews(item);
        if (readMap.get(item.id,false)) {
            holder.tvTitle.setTextColor(ContextCompat.getColor(holder.tvTitle.getContext(), R.color.gray60));
        } else {
            holder.tvTitle.setTextColor(ContextCompat.getColor(holder.tvTitle.getContext(), R.color.gray20));
        }
    }





    private static class NewsVH extends ViewHolder  {
        ImageView sdv;
        TextView tvTitle;
        TextView tvContent;

        private NewsVH(View itemView) {
            super(itemView);
            sdv = itemView.findViewById(R.id.sdv);
            tvTitle = itemView.findViewById(R.id.tv_title);
            tvContent = itemView.findViewById(R.id.tv_desc);
        }

        void bindNews(NewsModel item){
            sdv.setImageURI(UriUtil.parseUriOrNull(item.thumbImg));
        }
    }

    private static class NewsPic3VH extends NewsVH{

        ImageView sdv1;
        ImageView sdv2;

        private NewsPic3VH(View itemView) {
            super(itemView);

            sdv1 = itemView.findViewById(R.id.sdv1);
            sdv2 = itemView.findViewById(R.id.sdv2);
        }

        @Override
        void bindNews(NewsModel item){

            sdv.setImageURI(UriUtil.parseUriOrNull(item.images[0].imageUrl));
            sdv1.setImageURI(UriUtil.parseUriOrNull(item.images[1].imageUrl));
            sdv2.setImageURI(UriUtil.parseUriOrNull(item.images[2].imageUrl));
            //sdv.setImageURI(UriUtil.parseUriOrNull(item.thumbImg));
        }
    }

     private static class AD01VH extends ViewHolder{
        public ViewGroup container;
        private AD01VH(View view) {
            super(view);
            container =view.findViewById(R.id.express_ad_container);
        }
    }
}
